<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Method not allowed', 405);
}

// 获取请求数据
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || !isset($data['username']) || !isset($data['master_key_hash']) || !isset($data['device_id'])) {
    Response::error('Invalid request data');
}

$username = $data['username'];
$master_key_hash = $data['master_key_hash'];
$device_id = $data['device_id'];

try {
    // 检查用户名是否已存在
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        Response::error('Username already exists');
    }

    // 开始事务
    $pdo->beginTransaction();

    // 创建用户
    $stmt = $pdo->prepare("INSERT INTO users (username, master_key_hash) VALUES (?, ?)");
    $stmt->execute([$username, $master_key_hash]);
    $user_id = $pdo->lastInsertId();

    // 注册设备
    $stmt = $pdo->prepare("INSERT INTO sync_logs (user_id, device_id) VALUES (?, ?)");
    $stmt->execute([$user_id, $device_id]);

    // 提交事务
    $pdo->commit();

    Response::success([
        'user_id' => $user_id,
        'device_id' => $device_id
    ], 'Registration successful');
} catch (PDOException $e) {
    // 回滚事务
    $pdo->rollBack();
    Response::error('Database error: ' . $e->getMessage());
}
?> 